package pg

import (
	"database/sql"
	"fmt"
	"purchase-mall/conf"

	_ "github.com/jinzhu/gorm/dialects/postgres"
)

var db *sql.DB

// Init 初始化Pg连接
func Init(cfg *conf.PgConfig) (err error) {
	//fmt.Printf("PostgreSQL Switch %v\n", cfg.Switch)
	if cfg.Switch == false {
		return nil
	}
	dsn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", cfg.Host, cfg.Port, cfg.User, cfg.Password, cfg.DB)
	db, err = sql.Open("postgres", dsn)

	//db, err := sql.Open("postgres", "user=postgres password=abc123 dbname=daas_metric sslmode=disable")
	if err != nil {
		fmt.Printf("postgres db is err %s", err)
		return
	}
	//插入数据
	//stmt, err := db.Prepare("INSERT INTO metric_peak(type,type_name,metric,metric_name,peak_value,peak_time,max_value,created_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8)")
	//if err != nil {
	//	fmt.Printf("postgres stmt is err %s", err)
	//	println(err)
	//	return err
	//
	//}
	//res, err := stmt.Exec(1, "kafka", 1, "内存", 86.00, "2022-10-29 12:59:59", 90.99, "2022-10-29 12:59:00")
	//println(res)
	//if err != nil {
	//	fmt.Printf("postgres  res is err %s", err)
	//	println(err)
	//	return err
	//}
	return
}

// Close 关闭pg连接
func Close() {
	_ = db.Close()
}
